package com.a3dweijing.wetouch2.Activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.a3dweijing.wetouch2.Common.CallBack;
import com.a3dweijing.wetouch2.R;
import com.a3dweijing.wetouch2.network.Commsubscribe;
import com.a3dweijing.wetouch2.Util.GlideUtil;
import com.a3dweijing.wetouch2.Util.ProgressDialogHelp;
import com.a3dweijing.wetouch2.network.RetrofitUtil;
import com.a3dweijing.wetouch2.Util.ShareDialogHelp;
import com.a3dweijing.wetouch2.Util.Util;
import com.a3dweijing.wetouch2.wxapi.WXShareHelp;
import com.a3dweijing.wetouch2.View.AutoViewPager;
import com.a3dweijing.wetouch2.base.BaseFragmentActivity;
import com.a3dweijing.wetouch2.bean.GoodsInfoBean;
import com.a3dweijing.wetouch2.bean.ResultMsg;
import com.a3dweijing.wetouch2.bean.ShoppingDetails;
import com.a3dweijing.wetouch2.constant.Api;
import com.a3dweijing.wetouch2.datasave.Singleton;
import com.a3dweijing.wetouch2.fragment.ShoppingDetailsFragment;
import com.a3dweijing.wetouch2.fragment.ShoppingEvaluateFragment;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

import static com.a3dweijing.wetouch2.Activity.BuyActivity.BUYACTIVITYCODE;

public class ShoppingDetailsActivity extends BaseFragmentActivity
{
    
    @BindView(R.id.back)
    ImageView back;
    
    @BindView(R.id.top_text)
    TextView topText;
    
    @BindView(R.id.top_right)
    TextView topRight;
    
    @BindView(R.id.top_all)
    RelativeLayout topAll;
    
    @BindView(R.id.progressBar)
    ProgressBar progressBar;
    
    @BindView(R.id.loading_date)
    LinearLayout loadingDate;
    
    @BindView(R.id.resaut_status_img)
    ImageView resautStatusImg;
    
    @BindView(R.id.resaut_status)
    LinearLayout resautStatus;
    
    @BindView(R.id.name)
    TextView name;
    
    @BindView(R.id.desc)
    TextView desc;
    
    @BindView(R.id.money)
    TextView money;
    
    @BindView(R.id.money_bg)
    TextView moneyBg;
    
    @BindView(R.id.num)
    TextView num;
    
    @BindView(R.id.xiangqing)
    RadioButton xiangqing;
    
    @BindView(R.id.pingjia)
    RadioButton pingjia;
    
    @BindView(R.id.viewpager)
    AutoViewPager viewpager;
    
    @BindView(R.id.image_big)
    ImageView imageBig;
    
    @BindView(R.id.rg)
    RadioGroup rg;
    
    @BindView(R.id.buy_now)
    Button buyNow;
    
    @BindView(R.id.add_cart)
    Button addCart;
    
    @BindView(R.id.xing_img)
    ImageView xingImg;
    
    @BindView(R.id.collection)
    LinearLayout collection;
    
    @BindView(R.id.ll_share)
    LinearLayout llShare;
    
    private int id;
    
    public ShoppingDetails shoppingDetails;
    
    private ProgressDialog dialog;
    
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shopping_details);
        ButterKnife.bind(this);
        id = getIntent().getIntExtra("KEY", -1);
        if (-1 == id)
        {
            resautStatus.setVisibility(View.VISIBLE);
        }
        else
        {
            initDate();
        }
    }
    
    private void initView()
    {
        topText.setText("商品详情");
        setXingImg();
        if (dialog == null)
        {
            dialog = ProgressDialogHelp.create(this, "提示：", "正在提交中...", false);
        }
        GoodsInfoBean goodsInfo = shoppingDetails.getGoodsInfo();
        name.setText(goodsInfo.getS_goods_name());
        desc.setText(goodsInfo.getS_goods_describe());
        money.setText("￥：" + goodsInfo.getS_price());
        moneyBg.setText("原价：" + goodsInfo.getS_original_price());
        num.setText("销量：" + goodsInfo.getS_goods_sell_num() + "");
        moneyBg.setPaintFlags(Paint.STRIKE_THRU_TEXT_FLAG);
        GlideUtil.getInstance().showImage(this, goodsInfo.getS_goods_img_url_long(), imageBig);
        initFragment();
        setOnClick();
    }
    
    private void setXingImg()
    {
        if (shoppingDetails.getGoodsInfo().isCollection())
            xingImg.setImageDrawable(getResources().getDrawable(R.drawable.xing_yes));
        else
            xingImg.setImageDrawable(getResources().getDrawable(R.drawable.xing));
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == BUYACTIVITYCODE && resultCode == RESULT_OK)
        {
            OrderListActivity.startActivity(this, 0);
            finish();
        }
    }
    
    private void setOnClick()
    {
        llShare.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                share();
            }
        });
        collection.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                collection();
            }
        });
        buyNow.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                ArrayList<GoodsInfoBean> goodsInfoBeans = new ArrayList<>();
                goodsInfoBeans.add(shoppingDetails.getGoodsInfo());
                BuyActivity.startActivity(ShoppingDetailsActivity.this, goodsInfoBeans);
            }
        });
        addCart.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                if (!Util.isFastClick())
                    return;
                dialog.show();
                GoodsInfoBean goodsInfo = shoppingDetails.getGoodsInfo();
                Observable<ResultMsg> resultMsgObservable =
                    RetrofitUtil.getInstance().getApiOfPhp().addShoppingCart(goodsInfo.getS_goods_id(),
                        Integer.parseInt(Singleton.getInstance().getUser().getUser_id()),
                        "1",
                        goodsInfo.getS_price(),
                        goodsInfo.getS_goods_name(),
                        1 + "");
                new Commsubscribe<ResultMsg>().createSubscribe(resultMsgObservable,
                    dialog,
                    null,
                    disposables,
                    ShoppingDetailsActivity.this,
                    new CallBack()
                    {
                        @Override
                        public void doNext(int what, Object obj)
                        {
                            ResultMsg o = (ResultMsg)obj;
                            if (o.isFlag())
                            {
                                Toast.makeText(ShoppingDetailsActivity.this, "加入购物车成功...", Toast.LENGTH_SHORT).show();
                            }
                            else
                                Toast.makeText(ShoppingDetailsActivity.this, "加入购物车失败,请检查网络...", Toast.LENGTH_SHORT)
                                    .show();
                        }
                    });
            }
        });
        back.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                if (dialog.isShowing())
                {
                    dialog.dismiss();
                }
                else
                    finish();
            }
        });
        rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
        {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i)
            {
                if (i == R.id.xiangqing)
                {
                    viewpager.setCurrentItem(0);
                }
                else if (i == R.id.pingjia)
                    viewpager.setCurrentItem(1);
            }
        });
        viewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener()
        {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels)
            {
                
            }
            
            @Override
            public void onPageSelected(int position)
            {
                viewpager.resetHeight(position);
                if (position == 0)
                {
                    rg.check(R.id.xiangqing);
                }
                else
                    rg.check(R.id.pingjia);
            }
            
            @Override
            public void onPageScrollStateChanged(int state)
            {
                
            }
        });
        viewpager.resetHeight(0);
    }
    
    private void share()
    {
        ShareDialogHelp.create(this, new CallBack()
        {
            @Override
            public void doNext(int what, Object obj)
            {
                int i = -1;
                switch (what)
                {
                    case R.id.haoyou:
                        i = SendMessageToWX.Req.WXSceneSession;
                        break;
                    case R.id.pengyouquan:
                        i = SendMessageToWX.Req.WXSceneTimeline;
                        break;
                    case R.id.shouchang:
                        i = SendMessageToWX.Req.WXSceneFavorite;
                        break;
                }
                if (i != -1)
                    WXShareHelp.share(ShoppingDetailsActivity.this, i);
            }
        }).show();
        
    }
    
    private void collection()
    {
        int genre = 0;
        if (!shoppingDetails.getGoodsInfo().isCollection())
        {
            genre = 1;
        }
        else
            genre = 2;
        
        Observable<ResultMsg> observable = RetrofitUtil.getInstance().getApiOfPhp().collection(
            Integer.parseInt(Singleton.getInstance().getUser().getUser_id()),
            shoppingDetails.getGoodsInfo().getS_goods_id(),
            genre);
        observable.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(
            new Observer<ResultMsg>()
            {
                @Override
                public void onSubscribe(Disposable d)
                {
                    disposables.add(d);
                }
                
                @Override
                public void onNext(ResultMsg resultMsg)
                {
                    if (resultMsg.isFlag())
                    {
                        shoppingDetails.getGoodsInfo().setCollection(!shoppingDetails.getGoodsInfo().isCollection());
                    }
                    Toast.makeText(ShoppingDetailsActivity.this, resultMsg.getMessage(), Toast.LENGTH_SHORT).show();
                }
                
                @Override
                public void onError(Throwable e)
                {
                    setXingImg();
                    Toast.makeText(ShoppingDetailsActivity.this, "操作失败", Toast.LENGTH_SHORT).show();
                }
                
                @Override
                public void onComplete()
                {
                    setXingImg();
                }
            });
    }
    
    private void initFragment()
    {
        List<ShoppingDetails.ParticularsBean> particulars = shoppingDetails.getParticulars();
        ArrayList<String> pics = new ArrayList<>();
        ArrayList<Object> users = new ArrayList<>();
        for (ShoppingDetails.ParticularsBean particular : particulars)
        {
            pics.add(particular.getS_particulars_img_url());
        }
        List<ShoppingDetails.CommentBean> comment = shoppingDetails.getComment();
        for (ShoppingDetails.CommentBean commentBean : comment)
        {
            users.add(commentBean);
        }
        ArrayList<Fragment> fragments = new ArrayList<>();
        Bundle bundle = new Bundle();
        bundle.putStringArrayList("list", pics);
        Bundle bundle2 = new Bundle();
        bundle2.putSerializable("list", users);
        ShoppingDetailsFragment shoppingDetailsFragment = new ShoppingDetailsFragment();
        shoppingDetailsFragment.setArguments(bundle);
        fragments.add(shoppingDetailsFragment);
        ShoppingEvaluateFragment shoppingEvaluateFragment = new ShoppingEvaluateFragment();
        shoppingEvaluateFragment.setArguments(bundle2);
        fragments.add(shoppingEvaluateFragment);
        MyViewPager myViewPager = new MyViewPager(getSupportFragmentManager(), fragments);
        viewpager.setAdapter(myViewPager);
        viewpager.setObjectForPosition(fragments.get(0).getView(), 0);
        viewpager.setObjectForPosition(fragments.get(1).getView(), 1);
    }
    
    class MyViewPager extends FragmentPagerAdapter
    {
        ArrayList<Fragment> fragments;
        
        public MyViewPager(FragmentManager fm, ArrayList<Fragment> fragments)
        {
            super(fm);
            this.fragments = fragments;
        }
        
        @Override
        public Fragment getItem(int position)
        {
            return fragments.get(position);
        }
        
        @Override
        public int getCount()
        {
            return fragments.size();
        }
    }
    
    private void initDate()
    {
        loadingDate.setVisibility(View.VISIBLE);
        Api api = RetrofitUtil.getInstance().getApiOfPhp();
        Observable<ShoppingDetails> shoppingDetailsCall =
            api.shoppingDetails(id, Singleton.getInstance().getUser().getUser_id());
        shoppingDetailsCall.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(
            new Observer<ShoppingDetails>()
            {
                @Override
                public void onSubscribe(Disposable d)
                {
                    disposables.add(d);
                }
                
                @Override
                public void onNext(ShoppingDetails shoppingDetails)
                {
                    loadingDate.setVisibility(View.GONE);
                    ShoppingDetailsActivity.this.shoppingDetails = shoppingDetails;
                    if (shoppingDetails.isFlag())
                        initView();
                    else
                        resautStatus.setVisibility(View.VISIBLE);
                }
                
                @Override
                public void onError(Throwable e)
                {
                    loadingDate.setVisibility(View.GONE);
                    resautStatus.setVisibility(View.VISIBLE);
                }
                
                @Override
                public void onComplete()
                {
                    
                }
            });
    }
    
    public static void startActivity(Context context, int id)
    {
        if (Util.isFastClick())
        {
            Intent intent = new Intent();
            intent.putExtra("KEY", id);
            intent.setClass(context, ShoppingDetailsActivity.class);
            context.startActivity(intent);
        }
    }
}
